<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <meta http-equiv="X-UA-Compatible" content="IE=edge">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title>Document</title>
  <style>
    .a{
      position: fixed;
      left: 300px;
      top: 50px;
    }
    .backtop{
      position: fixed;
      bottom: 50px;
      right: 50px;
      display: none;
    }
  </style>
</head>
<body style="height: 3000px">
  <div id="app">
    <button class="a" @click="isShow = !isShow">
      {{ isShow?'消失':'显示' }}
    </button>
    <button v-if="isShow" class="backtop" v-backtop="200">回到顶部</button>
  </div>
  <script src="./vue.js"></script>
  <script>
    // 定义全局指令
    Vue.directive('backtop', {
      inserted(el,binding){
        window.onscroll = ()=>{
          const sTop = document.documentElement.scrollTop || document.body.scrollTop;
          console.log(sTop);
          if(sTop > binding.value){
            el.style.display = "block";
          } else {
            el.style.display = "none";
          }
        }

        el.onclick = ()=>{
          window.scrollTo(0,0);
        }
      },
      unbind(){
        console.log('解绑了');
        window.onscroll = null;
      }
    })
    const vm = new Vue({
      el: '#app',
      data: {
        isShow: true
      }
    })
  </script>
</body>
</html>